package lium.lbs.lbsim.activity

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.buz.hjcdriver.bean.TelphoneResultModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lmlibrary.Constants
import com.lmlibrary.bean.ResponseBean
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.fragment_friendslist.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.adapter.GetTelPhoneNumberAdapter
import lium.lbs.lbsim.utils.CharacterParser
import lium.lbs.lbsim.utils.PinnedHeaderItemDecoration
import lium.lbs.lbsim.utils.callbck.DialogCallback
import java.util.HashMap
import lium.lbs.lbsim.bean.PhoneInfo
import lium.lbs.lbsim.jgchat.utils.photovideo.takevideo.utils.LogUtils
import lium.lbs.lbsim.utils.GetPhoneNumberFromMobile
import lium.lbs.lbsim.utils.SpUtils


class GetTelNumberActivity : BaseActivity(), BaseQuickAdapter.OnItemClickListener {


    lateinit var adapter: GetTelPhoneNumberAdapter
    private val listData: ArrayList<TelphoneResultModel> = arrayListOf()
    var telphoneResultModel = arrayListOf<TelphoneResultModel>()

    var getPhoneNumberFromMobile: GetPhoneNumberFromMobile? = null
    var phoneList = ArrayList<PhoneInfo>()
    var phoneNumberString: String? = ""


    /**
     * 汉字转换成拼音的类
     */
    private var characterParser: CharacterParser? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_get_tel_number
    }


    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("添加好友")
        getPhoneNumberFromMobile = GetPhoneNumberFromMobile()
        phoneList = getPhoneNumberFromMobile?.getPhoneNumberFromMobile(this) as ArrayList<PhoneInfo>

        characterParser = CharacterParser.getInstance()
        adapter = GetTelPhoneNumberAdapter(listData)
        recyclerView.adapter = adapter
        adapter.disableLoadMoreIfNotFullPage(recyclerView) //关闭BRAVE的自动加载功能 改成 refreshLayout的上拉加载
        adapter.onItemClickListener = this
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        recyclerView.addItemDecoration(PinnedHeaderItemDecoration())

        mSidBar.setTextView(slide_dialog)
        mSidBar.setOnTouchingLetterChangedListener {
            //该字母首次出现的位置
            var position = 0
            for ((index, friend) in adapter.data.withIndex()) {
                if (TextUtils.equals(friend.letters, it.toUpperCase())) { //转为大写后 判断是否相同
                    position = index
                    if ("#" == it) {
                        position = -1 //不处理#
                    }
                    if ("A" == it) {
                        position = 1 //不处理#
                    }

                    break
                }
            }
            if (position != -1 && position != 0) {
                recyclerView.scrollToPosition(position)
                var mLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                mLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }

        /*   addDisposable(
               RxTextView.textChanges(search_myfriends)
                   .debounce(200, TimeUnit.MILLISECONDS)
                   .observeOn(AndroidSchedulers.mainThread())
                   .map(CharSequence::toString)
                   .subscribe {
                       getDataList(it)
                   })*/
    }

    fun getDataList() {
        phoneNumberString = ""
        for (i in 0..phoneList.size - 1) {
            if (i != 0) {
                phoneNumberString = phoneNumberString + ","
            }
            phoneNumberString = phoneNumberString + (phoneList as ArrayList<PhoneInfo>).get(i).number
        }
        val param = HashMap<String, String>()
        param["memberId"] = SpUtils.getInstance().get(Constants.memberId, "") as String
        param["phones"] = phoneNumberString.toString()

        postData(
            "/frinds/getmemberListByTXL",
            param,
            object : DialogCallback<ResponseBean<ArrayList<TelphoneResultModel>>>(this) {
                override fun onSuccess(response: Response<ResponseBean<ArrayList<TelphoneResultModel>>>) {
                    setDataList(response.body().data)
                }
            })
    }

    fun setDataList(list: ArrayList<TelphoneResultModel>) {

        telphoneResultModel.clear()

        for (i in 0..list.size - 1) {
            list.get(i).name = phoneList.get(i).name
            LogUtils.e("body--list--" + list.get(i).name)
        }

        if (list != null && !list.isEmpty()) {

            for (friend in list) {
                val pinyin = characterParser!!.getSelling(friend.name)
                val sortString = pinyin.substring(0, 1).toUpperCase()
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]".toRegex())) {
                    friend.letters = sortString.toUpperCase()
                } else {
                    friend.letters = "#"
                }
            }
            list.sortBy { it.letters }

            for ((index, bean) in list.withIndex()) {
                if (index == 0) {
                    telphoneResultModel.add(
                        0,
                        TelphoneResultModel("", "", "", "", "", "", bean.letters, TelphoneResultModel.ITEM_TYPE_SETION)
                    )
                    if (bean.isFriend.equals("0")){
                        telphoneResultModel.add(bean)
                    }
                } else {
                    if (TextUtils.equals(list[index - 1].letters, bean.letters)) { //判断上一个item缩写字母和当前的 是否一样
                        if (bean.isFriend.equals("0")){
                            telphoneResultModel.add(bean)
                        }
                    } else {
                        telphoneResultModel.add(
                            TelphoneResultModel(
                                "",
                                "",
                                "",
                                "",
                                "",
                                "",
                                bean.letters,
                                TelphoneResultModel.ITEM_TYPE_SETION
                            )
                        )
                        telphoneResultModel.add(bean)
                    }
                }
            }

        } else {
            show_no_friend.visibility = View.VISIBLE
        }
        for (i in 0..telphoneResultModel.size -1) {
            if (telphoneResultModel.get(i).isFriend.equals("1") ){
                telphoneResultModel.removeAt(i)
            }

        }
        adapter.data.clear()
        adapter.data.addAll(telphoneResultModel)
        adapter.loadMoreComplete()
        adapter.notifyDataSetChanged()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val intent = Intent()
        var tels = (adapter!!.data.get(position) as TelphoneResultModel).phone
        var contents = "大家都在尚聊，赶紧来啊！"
        intent.setAction(Intent.ACTION_SENDTO); //设置动作为发送短信
        intent.setData(Uri.parse("smsto:"+tels)); //设置发送的号码
        intent.putExtra("sms_body", contents); //设置发送的内容
        startActivity(intent);
    }

    override fun getNetWorkData() {
        getDataList()
    }

    override fun onClick(v: View?) {
    }
}
